﻿using System;
using System.Collections.Generic;

namespace Job.Core.Common
{
    /// <summary>
    /// Dictionary的扩展方法
    /// </summary>
    public static class DictionaryExtensions
    {
        /// <summary>
        /// 获得词典值I
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TType"></typeparam>
        /// <param name="dict"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static TType GetValue<TKey, TType>(this IDictionary<TKey, TType> dict, TKey key)
            where TKey : IComparable
        {
            if (dict.ContainsKey(key))
                return dict[key];
            else
                return default(TType);
        }

        /// <summary>
        /// 获得词典值II
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TType"></typeparam>
        /// <param name="dict"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static TType GetValue<TKey, TType>(this IDictionary<TKey, TType> dict, TKey key, TType defaultvalue)
            where TKey : IComparable
        {
            if (dict.ContainsKey(key))
                return dict[key];
            else
                return defaultvalue;
        }

        /// <summary>
        /// 设置词典值
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TType"></typeparam>
        /// <param name="dict"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static void SetValue<TKey, TType>(this IDictionary<TKey, TType> dict, TKey key, TType value)
            where TKey : IComparable
        {
            if (dict.ContainsKey(key))
                dict[key] = value;
            else
                dict.Add(key, value);
        }
    }
}
